//
//  RegisterPassWordViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/11.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "RegisterPassWordViewController.h"
#import "AgreementViewController.h"
#import "loginModel.h"
@interface RegisterPassWordViewController ()<UITextFieldDelegate>{
    NSTimer *_timer;
    int timecount;
    UIButton *hqBtn;
    BOOL _isTime;
    NSDate *saveDate;
}
@property (nonatomic,strong) UITextField *accTextField;
@property (nonatomic,strong) UITextField *pwdTextField;
@end

@implementation RegisterPassWordViewController
@synthesize accTextField,pwdTextField,tel;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:UIColorFromRGB(0xf2f2f2)];
    [self setView];
    [ [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
    saveDate = [NSDate dateWithTimeIntervalSinceNow:60];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
    // Do any additional setup after loading the view.
}
-(void)textChange
{
    UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
    UIButton *selectBtn = (UIButton *)[self.view viewWithTag:13];
    if (self.accTextField.text.length !=0 && self.pwdTextField.text.length != 0&&selectBtn.selected == YES) {
        if (![Unity isMsgCode:self.accTextField.text]) {
            [loginBtn setEnabled:NO];
            return;
        }
        [loginBtn setEnabled:YES];
    }else{
        [loginBtn setEnabled:NO];
    }
}
#pragma mark -- 获取验证码
-(void)getSms_code{
    TIME
    HEADDIC(nowTime, SMS_CODE);
    NSDictionary *body = @{
                           @"mode":@"1",
                           @"mobile":self.tel,
                           };
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result___%@",result);
    NSMutableDictionary *json = [result objectFromJSONString];
    if (json!=nil) {
        if ([[json objectForKey:@"err_code"] integerValue]==0) {
            saveDate = [NSDate dateWithTimeIntervalSinceNow:60];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
        }else{
            NSString *msg = [json objectForKey:@"err_title"];
            SHOW_TITLEALERT(@"提示", msg);
        }
    }
}
-(void)hqBtnClick{
    [self getSms_code];
}
-(void)verificationTime{
    int time = [saveDate timeIntervalSinceNow];
    
    if (time<0)
    {
        NSString *str = [NSString stringWithFormat:@"重新发送"];
        [hqBtn setEnabled:YES];
        [hqBtn setTitle:str forState:0];
    }
    else
    {
        NSString *str = [NSString stringWithFormat:@"%ds",time];
        [hqBtn setEnabled:NO];
        [hqBtn setTitle:str forState:0];
    }
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
}
-(void)setView{
    UIView *navView = [self createViewFrame:CGRectMake(0, 0, SWIDTH, 64) bgColor:UIColorFromRGB(0x247ac4) tag:0];
    [self.view addSubview:navView];
    [self.leftBtn setHidden:NO];
    [self.leftBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftBtn];
    [self.titleLab setText:self.title];
    [self.titleLab setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:self.titleLab];
    
    UIButton *btn1 = [UIButton buttonWithType:0];
    btn1.frame = CGRectMake(20, 20, 40, 44);
    [btn1 setBackgroundColor:[UIColor clearColor]];
    [btn1 addTarget:self action: @selector(backClick:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    UIView *tempView = [self createViewFrame:CGRectMake(10, 77, SWIDTH - 20, 85) bgColor:UIColorFromRGB(0xffffff) tag:0];
    tempView.layer.masksToBounds = YES;
    tempView.layer.cornerRadius = 6.0;
    tempView.layer.borderWidth = 0.6;
    tempView.layer.borderColor = [[UIColor whiteColor] CGColor];
    [self.view addSubview:tempView];
    
    UIView *lineView = [self createViewFrame:CGRectMake(0, 42, SWIDTH-20, 0.5) bgColor:[UIColor grayColor] tag:0];
    lineView.alpha = 0.2;
    [tempView addSubview:lineView];
    UIImageView *img1 = [self createImageViewFrame:CGRectMake(15, 11, 13, 20) image:nil imageName:@"验证码" tag:0];
    [tempView addSubview:img1];
    UIImageView *img2 = [self createImageViewFrame:CGRectMake(15, 54, 13, 20) image:nil imageName:@"登录密码" tag:0];
    [tempView addSubview:img2];
    
    self.accTextField = [self createTextFieldFrame:CGRectMake(36, 0, SWIDTH - 160, 42) bgColor:[UIColor clearColor] tag:10 keyBoardType:0];
    self.accTextField.textAlignment = NSTextAlignmentLeft;
    self.accTextField.delegate = self;
    self.accTextField.placeholder = @"验证码";
    self.accTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.accTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.accTextField.font = FONT14;
    [tempView addSubview:self.accTextField];

    UIView *line1 = [self createViewFrame:CGRectMake(SWIDTH - 40 - 85, 11, 0.5, 20) bgColor:UIColorFromRGB(0xe8e8e8) tag:0];
    [tempView addSubview:line1];
    
    hqBtn = [UIButton buttonWithType:0];
    hqBtn.frame = CGRectMake(SWIDTH - 122, 9, 80, 24);
    [hqBtn setBackgroundColor:[UIColor clearColor]];
    [hqBtn setTitleColor:BLUEColor forState:0];
    [tempView addSubview:hqBtn];
    hqBtn.clipsToBounds = YES;
    hqBtn.layer.cornerRadius = 5.0f;
    [hqBtn addTarget:self action:@selector(hqBtnClick) forControlEvents:7];
    hqBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    self.pwdTextField = [self createTextFieldFrame:CGRectMake(36, 43, SWIDTH - 53, 42) bgColor:[UIColor clearColor] tag:11 keyBoardType:0];
    self.pwdTextField.textAlignment = NSTextAlignmentLeft;
    self.pwdTextField.delegate = self;
    self.pwdTextField.placeholder = @"密码";
    self.pwdTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.pwdTextField.font = FONT14;
    [self.pwdTextField setSecureTextEntry:YES];
    [tempView addSubview:self.pwdTextField];
    
    UIButton *loginBtn = [self createButtonFrame:CGRectMake(10, 177, SWIDTH - 20, 43) title:@"注册" viewController:self selector:@selector(submit:) tag:12];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"登录-点击后按钮"] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = FONT14;
    [self.view addSubview:loginBtn];
    [loginBtn setEnabled:NO];
    
    UIButton *selectBtn = [self createButtonFrame:CGRectMake(10, 235, 13, 13) title:nil viewController:self selector:@selector(selectClick:) tag:13];
    selectBtn.selected = YES;
    [selectBtn setBackgroundImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
    [self.view addSubview:selectBtn];
    
    UILabel *lab1 = [self createLabelFrame:CGRectMake(27, 235, 55, 13) title:@"我同意" titleColor:UIColorFromRGB(0xbcbcbc) tag:0];
    [lab1 setFont:[UIFont systemFontOfSize:14]];
    [self.view addSubview:lab1];
    
    UIButton *lab2 = [self createButtonFrame:CGRectMake(55, 235, 180, 13) title:@"《有材网APP用户协议》" viewController:self selector:@selector(agreementClick:) tag:14];
    [lab2 setTitleColor:UIColorFromRGB(0x4f97e6) forState:UIControlStateNormal];
    [lab2.titleLabel setTextAlignment:NSTextAlignmentLeft];
    [lab2.titleLabel setFont:[UIFont systemFontOfSize:14]];
    lab2.selected = NO;
    [self.view addSubview:lab2];

    [self.accTextField becomeFirstResponder];
}

#pragma mark -- 登录
-(void)submit:(UIButton *)sender{
    if ([self.title isEqualToString:@"快捷登录"]) {
        //TODO:快捷登录
        [self requestLogin];
    }else {
        if (![Unity isMsgCode:self.accTextField.text]) {
            SHOW_TITLEALERT(@"提示", @"验证码有误");
            return;
        }
        [self requestRegister];
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
    if (textField == self.accTextField) {
        if (![string isEqualToString:@""]) {
            if (self.pwdTextField.text.length != 0) {
                [loginBtn setEnabled:YES];
            }else{
                [loginBtn setEnabled:NO];
            }
        }else{
            [loginBtn setEnabled:NO];
        }
    }
    
    if (textField == self.pwdTextField) {
        if (![string isEqualToString:@""]) {
            if (self.accTextField.text.length != 0) {
                [loginBtn setEnabled:YES];
            }else{
                [loginBtn setEnabled:NO];
            }
        }else{
            [loginBtn setEnabled:NO];
        }
    }
    
    return YES;
}

-(void)requestLogin{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *mobile = self.accTextField.text;
    BODYDIC(@"2", mobile, self.pwdTextField.text);
    TIME
    HEADDIC(nowTime,LOGIN);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:BODY forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSError *error;
    NSString *result = [request post:APPIP postDataDic:dic error:&error];
    NSLog(@"result__%@",result);
    if (result!=nil || ![result isEqualToString:@""]) {
        loginModel *loginInfo = [[loginModel alloc]init];
        [loginInfo parseResponseData:result];
        if ([loginInfo.err_code integerValue]==0) {
            loginModelObj *model = [loginInfo.data objectForKey:@"userInfo"];
            [[NSUserDefaults standardUserDefaults] setObject:model.certificate forKey:@"certificate"];
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
            [[NSUserDefaults standardUserDefaults] setObject:model.nickname forKey:@"nickname"];
            //                [[NSUserDefaults standardUserDefaults] setObject:model forKey:@"userInfo1"];
            if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
                [[NSUserDefaults standardUserDefaults] setObject:self.accTextField.text forKey:@"userIphone"];
            }
            
            [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"userPwd"];
            [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"newpassword"];
            [appStatus shareAppStatus].loginSuccess = @"1";
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}
-(void)requestRegister{
    TIME
    HEADDIC(nowTime, REGISTER);
    NSDictionary *body = @{
                           @"mobile": self.tel,
                           @"sms_code": self.accTextField.text,
                           @"password": self.pwdTextField.text,
                           @"client_model": [appStatus shareAppStatus].client_model,
                           @"client_os": [appStatus shareAppStatus].client_os,
                           @"client_os_version": [appStatus shareAppStatus].client_os_version,
                           @"client_latitude": [appStatus shareAppStatus].client_latitude,
                           @"client_longitude": [appStatus shareAppStatus].client_longitude,
                           @"client_device": [appStatus shareAppStatus].client_device,
                           @"app_version": APP_VERSION,
                           };
    NSMutableDictionary *dic= [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result___%@",result);
    NSMutableDictionary *json = [result objectFromJSONString];
    NSString *err_code = [[json objectForKey:@"err_code"] stringValue];
    if (![err_code isEqualToString:@"0"]) {
        SHOW_ALERT([json objectForKey:@"err_message"]);
        return;
    }
    NSMutableDictionary *data = [json objectForKey:@"data"];
    [appStatus shareAppStatus].certificate = [data objectForKey:@"certificate"];
    [[NSUserDefaults standardUserDefaults] setObject:[data objectForKey:@"certificate"] forKey:@"certificate"];
    [[NSUserDefaults standardUserDefaults] setObject:[data objectForKey:@"nickname"] forKey:@"nickname"];
    [[NSUserDefaults standardUserDefaults] setObject:[data objectForKey:@"mobile"] forKey:@"userIphone"];
    [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"userPwd"];
    [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"newpassword"];
    [appStatus shareAppStatus].loginSuccess = @"1";
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark -- 选择协议
-(void)agreementClick:(UIButton *)sender{
    AgreementViewController *agreementVC = [[AgreementViewController alloc]init];
    agreementVC.title = @"有材协议";
    [self.navigationController pushViewController:agreementVC animated:YES];
}
-(void)selectClick:(UIButton *)sender{
    UIButton *button =(UIButton *)sender;
    UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
    if (button.selected == NO) {
        button.selected = YES;
        [button setBackgroundImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        if (self.accTextField.text.length != 0&&self.pwdTextField.text.length !=0  && button.selected == YES) {
            [loginBtn setEnabled:YES];
        }else{
            [loginBtn setEnabled:NO];
        }
    }else{
        button.selected = NO;
        [button setBackgroundImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateNormal];
        if (self.accTextField.text.length != 0&&self.pwdTextField.text.length !=0  && button.selected == YES) {
            [loginBtn setEnabled:YES];
        }else{
            [loginBtn setEnabled:NO];
        }
    }
}

-(void)backClick:(UIButton *)sender{
    dispatch_async(dispatch_get_main_queue(), ^{
        _isTime = NO;
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册尚未完成，是否继续操作" delegate:self cancelButtonTitle:@"继续" otherButtonTitles:@"退出", nil];
        [alert setTag:110];
        [alert show];
    });
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 110) {
        if (buttonIndex == 1) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
